/*
 * Copyright 2013, NuzoweR@Schneefeuer <nuzower@gmail.com>.
 * The Settlers Online - Combat Simulator (tsosim).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Debug.h"
#include "SimParser.h"
#include "Simulator.h"
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <version.h>

int version_number()
{
	return 1;
}

void print_header(std::ostream& OUT)
{
	OUT << "The Settlers Online - Combat Simulator (tsosim - v" << version_number() << ":" << BUILD_VERSION << ").\n"
		<< "Copyright (c) 2013, NuzoweR@Schneefeuer.\n"
		<< std::endl;
}

void print_usage(std::ostream& OUT)
{
	OUT << "Usage : \n"
		<< "  tsosim input_file [options]\n"
		<< "\n"
		<< "Options : \n"
		<< "  -out output_file                   - write results into file instead of in standard out\n"
		<< "  -debug {DEBUG|INFO|WARNING|ERROR}  - choose debug level, most informative(DEBUG) to least informative(ERROR)\n"
		<< std::endl;
}

int main(int argc, char** argv)
{

	std::string infile;
	std::string outfile;

	// ignore first argument (program name)
	argv++;

	while(argv && *argv)
	{
		if( *argv == std::string("-out") ) {
			argv++;
			if(argv && *argv) {
				outfile = *argv;
			}
			else {
				print_header(std::cout);
				print_usage(std::cout);
				exit(1);
			}
		}
		else if( *argv == std::string("-debug") ) {
			argv++;
			if(!debug::SetLevel(*argv))
			{
				print_header(std::cout);

				std::cout << "ERROR : unknown debug level : " << *argv << std::endl << std::endl;
				print_usage(std::cout);
				exit(1);
			}
		}
		else {
			infile = *argv;
		}

		argv++;
	}


	if(infile.empty()) {
		print_header(std::cout);
		std::cout << "ERROR : no file!" << std::endl << std::endl;
		print_usage(std::cout);
		exit(1);
	}

	std::ofstream FILE;

	if(!outfile.empty())
	{
		Simulator::set_ostream(outfile);
	}

	print_header(*Simulator::get_ostream());

	if(debug::CheckLevel(debug::DL_DEBUG))
	{
		std::ostream& OUT = *Simulator::get_ostream();
		OUT << "IN  : " << infile  << std::endl;
		OUT << "OUT : " << outfile << std::endl;
	}


	if(!infile.empty())
	{
		SimParser parser;
		parser.process_file(infile);
	}

	return 0;
}
